<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\MyLog;
use App\Models\Mongodb;
use App\Models\Wallet;
use App\Models\Tixian;

require_once('config.php');
require_once('function.php');
require_once('moban.php');

class ShenheController extends Controller
{
      public function index(Request $request){
        $start = $request->start;
        $end = $request->end;
         $tixian = round(DB::table('shenhe')->sum('price'),2);
         $pass = round(DB::table('shenhe')->where('status',1)->sum('price'),2);
        if ($start && $end) {
            $status = 1;
            $where = [
                ['shenhe.created_at','>=',strtotime($start)],
                ['shenhe.created_at','<=',strtotime($end)]
            ];
             $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
             ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
             ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
             ->where($where)
             ->orderBy('shenhe.id', 'desc')
             ->paginate(15);
             return view('admin.shenhe.index',compact('data','tixian','pass','status'));exit;
        } elseif ($start) {
            $status = 1;
            $where = [
                ['shenhe.created_at','>=',strtotime($start)],
            ];
             $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
             ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
             ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
             ->where($where)->orderBy('shenhe.id', 'desc')
             ->paginate(15);
             return view('admin.shenhe.index',compact('data','tixian','pass','status'));exit;
        }elseif ($end) {
            $status = 1;
            $where = [
                ['shenhe.created_at','<=',strtotime($end)],
            ];
             $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
             ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
             ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
             ->where($where)
             ->orderBy('shenhe.id', 'desc')
             ->paginate(15);
             return view('admin.shenhe.index',compact('data','tixian','pass','status'));exit;
        }
         $status = 0;
         $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
                                     ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
                                     ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
                                     ->where('shenhe.status',0)
                                     ->orderBy('shenhe.id', 'desc')
                                     ->paginate(15);
         return view('admin.shenhe.index',compact('data','tixian','status','pass'));exit;
      }

      public function haspass(){
         $tixian = round(DB::table('shenhe')->sum('price'),2);
         $pass = round(DB::table('shenhe')->where('status',1)->sum('price'),2);
         $status = 1;
         $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
                                   ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
                                     ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
                                   ->where('shenhe.status',1)
                                   ->orderBy('shenhe.id', 'desc')
                                   ->paginate(15);
         return view('admin.shenhe.index',compact('data','tixian','status','pass'));
      }

      public function nopass(){
        $tixian = round(DB::table('shenhe')->sum('price'),2);
         $pass = round(DB::table('shenhe')->where('status',1)->sum('price'),2);
        $status = 2;
         $data = DB::table('shenhe')->select('shenhe.*','wallet.money','user.username')
         ->leftJoin('wallet', 'shenhe.openid', '=', 'wallet.openid')
         ->leftJoin('user', 'shenhe.openid', '=', 'user.open_id')
         ->where('shenhe.status','>=',2)
         ->orderBy('shenhe.id', 'desc')
         ->paginate(15);
         return view('admin.shenhe.index',compact('data','tixian','status','pass'));
      }

      //通过
      public function pass(Request $request){
         $id = $request->id;
         $data = DB::table('shenhe')->where('id',$id)->first();
         if ($data->status != 0) {
            echo json_encode(['status'=>0,'msg'=>'不能重复修改']);exit;
         }
         $result = $this->tixian($data->openid,$data->price,$data->formid);
         if ($result == 'success') {
            DB::table('shenhe')->where('id',$id)->update(['status'=>1]);
            //提现审核通过写入日志
             $this->withdraw($data->openid,$data->price);
             $arr = [
               'status' => 1,
               'msg' => '成功'
            ];
         }elseif($result == '当天提现次数超额') {
            DB::table('shenhe')->where('id',$id)->update(['content'=>$result]);
            $arr = [
               'status' => 0,
               'msg' => $result
            ];
         }else{
            DB::table('shenhe')->where('id',$id)->update(['content'=>$result,'status'=>3]);
            $arr = [
               'status' => 0,
               'msg' => $result
            ];
         }
         echo json_encode($arr);
      }

      //不通过
      public function fail(Request $request){
         $id = $request->id;
         $why = $request->why; //不通过原因
         if ($why == '' || $id == '') {
             $arr = [
               'status' => 0,
               'msg' => '原因或id不能为空'
            ];
            echo json_encode($arr);exit();
         }
         $data = DB::table('shenhe')->where('id',$id)->first();
         if ($data->status != 0) {
            echo json_encode(['status'=>0,'msg'=>'不能重复修改']);exit;
         }
         $in = DB::table('wallet')->where('openid',$data->openid)->increment('money',$data->price);
         if ($in) {
             $update = DB::table('shenhe')->where('id',$id)->update(['status'=>2,'content'=>$why]);
             $this->failtemplateInfo($data->price,$data->openid,$data->formid,$why,$data->created_at);
             echo json_encode(['status' => 1,'msg' => '申请id为'.$id.'修改成功']);exit;
         }
         echo json_encode(['status' => 0,'msg' => '修改失败']);exit;
      }

        private function tixian($cpy_openid,$price,$formId)
         {

           /*
           * 配置内容可以修改
           * 微信小程序配置
           * 用于微信企业付款
           */

           $cpy_appid = 'wx45ae814068d167a3';                  //小程序appid
           $cpy_mchid = '1233747002';                          //商户id
           $cpy_key = 'FgfdDGsV567ADSFsddVLK554642DddSm';      //商户key
           $cpy_secret = '0317b21c0d97d4f7aa379c5391fd6a02';   //公众号secret
           $cpy_nonce_str = time() . rand(100000, 999999);   //随机字符串
           $cpy_order_str = time() . rand(100000, 999999); // 唯一订单号

           if ($cpy_openid == '' || $price == '') {
               echo 'not';
               exit;
           }

           //开启事务
           DB::beginTransaction();
           try {
               $arr = [
                   'openid' => $cpy_openid,
                   'price' => $price,
                   'type' => 1
               ];
               $insertId = DB::table('tixian')->insertGetId($arr);

               //封装数据
               $ip = $_SERVER['REMOTE_ADDR'];
               $dataArr = array(
                   'mch_appid' => $cpy_appid,
                   'mchid' => $cpy_mchid,
                   'nonce_str' => $cpy_nonce_str,
                   'partner_trade_no' => $cpy_order_str,
                   'openid' => $cpy_openid,
                   'check_name' => 'NO_CHECK', //NO_CHECK 小额不校验真实姓名
                   're_user_name' => 'test', //填写对应openid真实姓名
                   'amount' => $price * 100, //以分为单位,必须大于100
                   'desc' => '提现成功',  //入账详情
                   'spbill_create_ip' => $ip,
               );
               //生成签名
               $sign = getSign($dataArr, $cpy_key);
               $xml = '<xml>
                       <mch_appid>' . $dataArr['mch_appid'] . '</mch_appid>
                       <mchid>' . $dataArr['mchid'] . '</mchid>
                       <nonce_str>' . $dataArr['nonce_str'] . '</nonce_str>
                       <partner_trade_no>' . $dataArr['partner_trade_no'] . '</partner_trade_no>
                       <openid>' . $dataArr['openid'] . '</openid>
                       <check_name>' . $dataArr['check_name'] . '</check_name>
                       <re_user_name>' . $dataArr['re_user_name'] . '</re_user_name>
                       <amount>' . $dataArr['amount'] . '</amount>
                       <desc>' . $dataArr['desc'] . '</desc>
                       <spbill_create_ip>' . $dataArr['spbill_create_ip'] . '</spbill_create_ip>
                       <sign>' . $sign . '</sign>
                       </xml>';
               $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
               if ($insertId) {
                   $res = xmlToArray(postXmlCurl($xml, $url, true));
                   $result = $this->update_money($cpy_openid, $price, $res, $formId,$insertId);
                   DB::commit();
                   return $result;exit;
               }
           } catch (\Exception $e) {
                DB::rollBack();
                $mylog = new MyLog;
                $mylog->setLog('人工提现数据:'.$e,$logPath='tixian(rengong)');
                return 'error';exit;
           }
       }

       //修改用户余额
       private function update_money($cpy_openid, $price, $res, $formId,$insertId)
       {
           if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
               //记录提现
               $arr = [
                   'partner_trade_no' => $res['partner_trade_no'],
                   'payment_no' => $res['payment_no'],
                   'payment_time' => $res['payment_time'],
                   'created_at' => time(),
                   'status' => 1
               ];
               DB::table('tixian')->where('id',$insertId)->update($arr);
               //发送模板消息调用(提现成功)
               $this->templateInfo($price, $res, $cpy_openid, $formId);
               return 'success';
           }elseif ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL' && $res['err_code'] == 'SENDNUM_LIMIT') {//当天提现次数超额，返回提示
               $arr = [
                   'err_code' => $res['err_code_des'],
                   'created_at' => time()
               ];
               DB::table('tixian')->where('id',$insertId)->update($arr);
               return '当天提现次数超额'; //超额提示
           } elseif ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL') {//通信成功，但交易失败，写入数据库
               $arr = [
                   'err_code' => $res['err_code_des'],
                   'created_at' => time()
               ];
               DB::table('tixian')->where('id',$insertId)->update($arr);
               return $res['err_code_des']; //联系管理员
           }else {//通讯失败，返回错误
               return 'error';
           }
       }

       //提现成功模板消息
        public function templateInfo($price, $res, $cpy_openid, $formId)
         {
              $moban = new \Moban();
              $mobanData = [
                  'keyword1' => ['value' => $price . '元'],
                  'keyword2' => ['value' => $res['payment_time']],
                  'keyword3' => ['value' => '微信钱包'],
                  'keyword4' => ['value' => '请注意查收']
              ];
              $get = $moban->send($cpy_openid, 'ztcKAjmN4w7hjsF02f5Xlyv74SlGpcLHcZREgd3JX4c', 'pages/voice_box/mention/index', $formId, $mobanData);
              //将回调数据写入日志
              $tuiData = '[openid]' . $cpy_openid . '[price]' . $price . '[errmsg]' . $get->errmsg;
              $mylog = new MyLog;
              $mylog->setLog('人工提现数据:' . $tuiData, $logPath = 'moban(tixian-ren)');

         }

         //提现失败模板消息
         public function failtemplateInfo($price,$cpy_openid, $formId , $why , $time)
         {
              $moban = new \Moban();
              $mobanData = [
                  'keyword1' => ['value' => $price . '元'],
                  'keyword2' => ['value' => date('Y/m/d H:i:s',$time)],
                  'keyword3' => ['value' => $why],
              ];
              $get = $moban->send($cpy_openid, 'b3whSRIXw47ptXR_TiNfH5-4E8fDlhMe8Y6rPxBM7Pk', 'pages/voice_box/mention/index', $formId, $mobanData);
              //将回调数据写入日志
              $tuiData = '[openid]' . $cpy_openid . '[price]' . $price . '[errmsg]' . $get->errmsg;
              $mylog = new MyLog;
              $mylog->setLog('用户提现数据:' . $tuiData, $logPath = 'moban(tixian-ren)');

         }

          //红包明细
         public function reddetail(Request $request){
              $openid = $request->openid ;
              $type = $request->type ;
              // $openid = 'okfAV0dqL0t4oeKw9zsB9_n4lgg8';
              $redfdata = DB::table('redf')->select('sign','created_at','price')->where([['openid','=',$openid],['status','=',1]])->get();
              $redsdata = DB::table('reds')->select('sign','price','created_at')->where([['openid','=',$openid],['sign','=',1]])->orWhere([['openid','=',$openid],['sign','=',2],['is_correct','=',1]])->get();
              $tixiandata = DB::table('tixian')->select('created_at','price')->where([['openid','=',$openid],['status','=',1]])->get();
              $shenhedata = DB::table('shenhe')->select('created_at','price')->where([['openid','=',$openid],['status','=',0]])->get();

              foreach ($redfdata as $value) {
                      $value->type = 0 ;
              }
              foreach ($redsdata as $value) {
                      $value->type = 1 ;
              }
              foreach ($tixiandata as $value) {
                      $value->type = 2 ;
                      $value->sign = 0 ;
              }
              foreach ($shenhedata as $value) {
                      $value->type = 3;
                      $value->sign = 0;
              }



              $redfdata = json_decode(json_encode($redfdata), true);
              $redsdata = json_decode(json_encode($redsdata), true);
              $tixiandata = json_decode(json_encode($tixiandata), true);
              $shenhedata = json_decode(json_encode($shenhedata), true);
              $data = array_merge($redfdata,$redsdata,$tixiandata,$shenhedata) ;
              $info = array_column($data, 'created_at');
              array_multisort($info,SORT_DESC,$data);
              if ($type != '' && $type == 0) {
                 $data = $redfdata;
              }elseif($type != '' && $type == 1){
                 $data = $redsdata;
              }elseif ($type != '' && $type == 2) {
                 $data = $tixiandata;
              }elseif ($type != '' && $type == 3) {
                 $data = $shenhedata;
              }

                return view('admin.shenhe.detail',compact('data','openid'));

         }

         //提现成功日志记录
         public function withdraw($openid,$price){
             $adminName = auth()->guard('admin')->user()->name;
             $logs = Mongodb::connectionMongodb('hb_log');
             $logs->insert(['order_sn' => $adminName, 'openid' => $openid, 'type' => '5', 'name' => '是提现审核通过', 'message' => $price, 'log_time' => date("Y-m-d H:i")]);
         }

}
